package de.justphil.tcg.tcgserver.commons.util;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import de.justphil.tcg.tcgserver.commons.config.I18nConfig;
import net.jcip.annotations.ThreadSafe;

@ThreadSafe
public final class LanguageFileLoader {

	public static List<String> getLanguageFiles(String packagePath,
			String bundleName) throws UnsupportedEncodingException {
		File root = new File(LanguageFileLoader.class.getResource(packagePath)
				.getFile());
		root = new File(URLDecoder.decode(root.getAbsolutePath(), "UTF-8"));

		final String bName = bundleName;
		File[] files = root.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.matches("^" + bName
						+ "(_\\w{2}(_\\w{2})?)?\\.properties$");
			}
		});

		if (files == null || files.length == 0) {
			return null;
		}

		List<String> languageMap = new ArrayList<String>(files.length);
		String s;
		for (File file : files) {
			s = file.getName().replaceAll(
					"^" + bundleName + "(_)?|\\.properties$", "");
			
			s = s.replace("_", "-");
			
			if (s.trim().length() == 0) {
				languageMap.add(I18nConfig.DEFAULT_LOCALE);
			} else {
				languageMap.add(s);
			}
		}

		return languageMap;
	}
	
}
